<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0">
        <meta property="og:image" content="https://assets.khoj.dev/khoj_hero.png">
        <title>Khoj - Chat</title>

        <link rel="stylesheet" href="/static/assets/khoj.css?v={{ khoj_version }}">
        <link rel="icon" type="image/png" sizes="128x128" href="/static/assets/icons/favicon-128x128.png?v={{ khoj_version }}">
        <link rel="apple-touch-icon" href="/static/assets/icons/favicon-128x128.png?v={{ khoj_version }}">
        <link rel="manifest" href="/static/khoj.webmanifest?v={{ khoj_version }}">
        <link rel="stylesheet" href="https://assets.khoj.dev/katex/katex.min.css">

        <!-- The loading of KaTeX is deferred to speed up page rendering -->
        <script defer src="https://assets.khoj.dev/katex/katex.min.js"></script>

        <!-- To automatically render math in text elements, include the auto-render extension: -->
        <script defer src="https://assets.khoj.dev/katex/auto-render.min.js" onload="renderMathInElement(document.body);"></script>
    </head>
    <script type="text/javascript" src="/static/assets/utils.js?v={{ khoj_version }}"></script>
    <script type="text/javascript" src="/static/assets/markdown-it.min.js?v={{ khoj_version }}"></script>
    <script>
        let welcome_message = `
Hi, I am Khoj, your open, personal AI 👋🏽. I can:
- 🧠 Answer general knowledge questions
- 💡 Be a sounding board for your ideas
- 📜 Chat with your notes & documents
- 🌄 Generate images based on your messages
- 🔎 Search the web for answers to your questions
- 🎙️ Listen to your audio messages (use the mic by the input box to speak your message)
- 📚 Understand files you drag & drop here
- 👩🏾‍🚀 Be tuned to your conversation needs via [agents](./agents)

Get the Khoj [Desktop](https://khoj.dev/downloads), [Obsidian](https://docs.khoj.dev/clients/obsidian#setup), [Emacs](https://docs.khoj.dev/clients/emacs#setup) apps to search, chat with your 🖥️ computer docs. You can manage all the files you've shared with me at any time by going to [your settings](/config/content-source/computer/).

To get started, just start typing below. You can also type / to see a list of commands.
`.trim()
        const allowedExtensions = ['text/org', 'text/markdown', 'text/plain', 'text/html', 'application/pdf'];
        const allowedFileEndings = ['org', 'md', 'txt', 'html', 'pdf'];
        let chatOptions = [];
        function createCopyParentText(message) {
            return function(event) {
                copyParentText(event, message);
            }
        }
        function copyParentText(event, message=null) {
            const button = event.currentTarget;
            const textContent = message ?? button.parentNode.textContent.trim();
            navigator.clipboard.writeText(textContent).then(() => {
                button.firstChild.src = "/static/assets/icons/copy-button-success.svg";
                setTimeout(() => {
                    button.firstChild.src = "/static/assets/icons/copy-button.svg";
                }, 1000);
            }).catch((error) => {
                console.error("Error copying programmatic output to clipboard:", error);
                const originalButtonText = button.innerHTML;
                button.innerHTML = "⛔️";
                setTimeout(() => {
                    button.innerHTML = originalButtonText;
                    button.firstChild.src = "/static/assets/icons/copy-button.svg";
                }, 1000);
            });
        }
        var websocket = null;
        let region = null;
        let city = null;
        let countryName = null;
        let timezone = null;
        let waitingForLocation = true;

        let websocketState = {
            newResponseTextEl: null,
            newResponseEl: null,
            loadingEllipsis: null,
            references: {},
            rawResponse: "",
        }

        fetch("https://ipapi.co/json")
            .then(response => response.json())
            .then(data => {
                region = data.region;
                city = data.city;
                countryName = data.country_name;
                timezone = data.timezone;
            })
            .catch(err => {
                console.log(err);
                return;
            })
            .finally(() => {
                console.debug("Region:", region, "City:", city, "Country:", countryName, "Timezone:", timezone);
                waitingForLocation = false;
                setupWebSocket();
            });

        function formatDate(date) {
            // Format date in HH:MM, DD MMM YYYY format
            let time_string = date.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: false });
            let date_string = date.toLocaleString('en-IN', { year: 'numeric', month: 'short', day: '2-digit'}).replaceAll('-', ' ');
            return `${time_string}, ${date_string}`;
        }

        function generateReference(referenceJson, index) {
            let reference = referenceJson.hasOwnProperty("compiled") ? referenceJson.compiled : referenceJson;
            let referenceFile = referenceJson.hasOwnProperty("file") ? referenceJson.file : null;

            // Escape reference for HTML rendering
            let escaped_ref = reference.replaceAll('"', '&quot;');

            // Generate HTML for Chat Reference
            let short_ref = escaped_ref.slice(0, 140);
            short_ref = short_ref.length < escaped_ref.length ? short_ref + "..." : short_ref;
            let referenceButton = document.createElement('button');
            referenceButton.textContent = short_ref;
            referenceButton.id = `ref-${index}`;
            referenceButton.classList.add("reference-button");
            referenceButton.classList.add("collapsed");
            referenceButton.tabIndex = 0;

            // Add event listener to toggle full reference on click
            referenceButton.addEventListener('click', function() {
                if (this.classList.contains("collapsed")) {
                    this.classList.remove("collapsed");
                    this.classList.add("expanded");
                    this.textContent = escaped_ref;
                } else {
                    this.classList.add("collapsed");
                    this.classList.remove("expanded");
                    this.textContent = short_ref;
                }
            });

            return referenceButton;
        }

        function generateOnlineReference(reference, index) {

            // Generate HTML for Chat Reference
            let title = reference.title || reference.link;
            let link = reference.link;
            let snippet = reference.snippet;
            let question = reference.question;
            if (question) {
                question = `<b>Question:</b> ${question}<br><br>`;
            } else {
                question = "";
            }

            let linkElement = document.createElement('a');
            linkElement.setAttribute('href', link);
            linkElement.setAttribute('target', '_blank');
            linkElement.setAttribute('rel', 'noopener noreferrer');
            linkElement.classList.add("reference-link");
            linkElement.setAttribute('title', title);
            linkElement.textContent = title;

            let referenceButton = document.createElement('button');
            referenceButton.innerHTML = linkElement.outerHTML;
            referenceButton.id = `ref-${index}`;
            referenceButton.classList.add("reference-button");
            referenceButton.classList.add("collapsed");
            referenceButton.tabIndex = 0;

            // Add event listener to toggle full reference on click
            referenceButton.addEventListener('click', function() {
                if (this.classList.contains("collapsed")) {
                    this.classList.remove("collapsed");
                    this.classList.add("expanded");
                    this.innerHTML = linkElement.outerHTML + `<br><br>${question + snippet}`;
                } else {
                    this.classList.add("collapsed");
                    this.classList.remove("expanded");
                    this.innerHTML = linkElement.outerHTML;
                }
            });

            return referenceButton;
        }
        var khojQuery = "";
        function renderMessage(message, by, dt=null, annotations=null, raw=false, renderType="append", userQuery=null) {
            let message_time = formatDate(dt ?? new Date());
            let by_name =  by == "khoj" ? "🏮 Khoj" : "🤔 You";
            let formattedMessage = formatHTMLMessage(message, raw, true, userQuery);
            //update userQuery or khojQuery to latest query for feedback purposes
            if(by !== "khoj"){
                raw = formattedMessage.innerHTML;
            }

            //find the thumbs up and thumbs down buttons from the message formatter
            var thumbsUpButtons = formattedMessage.querySelectorAll('.thumbs-up-button');
            var thumbsDownButtons = formattedMessage.querySelectorAll('.thumbs-down-button');

            //only render the feedback options if the message is a response from khoj
            if(by !== "khoj"){
                thumbsUpButtons.forEach(function(element) {
                    element.parentNode.removeChild(element);
                });
                thumbsDownButtons.forEach(function(element) {
                    element.parentNode.removeChild(element);
                });
            }


            // Create a new div for the chat message
            let chatMessage = document.createElement('div');
            chatMessage.className = `chat-message ${by}`;
            chatMessage.dataset.meta = `${by_name} at ${message_time}`;

            // Create a new div for the chat message text and append it to the chat message
            let chatMessageText = document.createElement('div');
            chatMessageText.className = `chat-message-text ${by}`;
            chatMessageText.appendChild(formattedMessage);
            chatMessage.appendChild(chatMessageText);

            // Append annotations div to the chat message
            if (annotations) {
                chatMessageText.appendChild(annotations);
            }

            // Append chat message div to chat body
            let chatBody = document.getElementById("chat-body");
            if (renderType === "append") {
                chatBody.appendChild(chatMessage);
                // Scroll to bottom of chat-body element
                chatBody.scrollTop = chatBody.scrollHeight;
            } else if (renderType === "prepend"){
                let chatBody = document.getElementById("chat-body");
                chatBody.insertBefore(chatMessage, chatBody.firstChild);
            } else if (renderType === "return") {
                return chatMessage;
            }

            let chatBodyWrapper = document.getElementById("chat-body-wrapper");
            chatBodyWrapperHeight = chatBodyWrapper.clientHeight;
        }

        function processOnlineReferences(referenceSection, onlineContext) {
            let numOnlineReferences = 0;
            for (let subquery in onlineContext) {
                let onlineReference = onlineContext[subquery];
                if (onlineReference.organic && onlineReference.organic.length > 0) {
                    numOnlineReferences += onlineReference.organic.length;
                    for (let index in onlineReference.organic) {
                        let reference = onlineReference.organic[index];
                        let polishedReference = generateOnlineReference(reference, index);
                        referenceSection.appendChild(polishedReference);
                    }
                }

                if (onlineReference.knowledgeGraph && onlineReference.knowledgeGraph.length > 0) {
                    numOnlineReferences += onlineReference.knowledgeGraph.length;
                    for (let index in onlineReference.knowledgeGraph) {
                        let reference = onlineReference.knowledgeGraph[index];
                        let polishedReference = generateOnlineReference(reference, index);
                        referenceSection.appendChild(polishedReference);
                    }
                }

                if (onlineReference.peopleAlsoAsk && onlineReference.peopleAlsoAsk.length > 0) {
                    numOnlineReferences += onlineReference.peopleAlsoAsk.length;
                    for (let index in onlineReference.peopleAlsoAsk) {
                        let reference = onlineReference.peopleAlsoAsk[index];
                        let polishedReference = generateOnlineReference(reference, index);
                        referenceSection.appendChild(polishedReference);
                    }
                }

                if (onlineReference.webpages && onlineReference.webpages.length > 0) {
                    numOnlineReferences += onlineReference.webpages.length;
                    for (let index in onlineReference.webpages) {
                        let reference = onlineReference.webpages[index];
                        let polishedReference = generateOnlineReference(reference, index);
                        referenceSection.appendChild(polishedReference);
                    }
                }
            }

            return numOnlineReferences;
        }

        function renderMessageWithReference(message, by, context=null, dt=null, onlineContext=null, intentType=null, inferredQueries=null) {
            let chatEl;
            if (intentType?.includes("text-to-image")) {
                let imageMarkdown = generateImageMarkdown(message, intentType, inferredQueries);
                chatEl = renderMessage(imageMarkdown, by, dt, null, false, "return");
            } else {
                chatEl = renderMessage(message, by, dt, null, false, "return");
            }

            // If no document or online context is provided, render the message as is
            if ((context == null || context?.length == 0)
                && (onlineContext == null || (onlineContext && Object.keys(onlineContext).length == 0))) {
                return chatEl;
            }

            // If document or online context is provided, render the message with its references
            let references = {};
            if (!!context) references["notes"] = context;
            if (!!onlineContext) references["online"] = onlineContext;
            let chatMessageEl = chatEl.getElementsByClassName("chat-message-text")[0];
            chatMessageEl.appendChild(createReferenceSection(references));

            return chatEl;
        }

        function generateImageMarkdown(message, intentType, inferredQueries=null) {
            let imageMarkdown;
            if (intentType === "text-to-image") {
                imageMarkdown = `![](data:image/png;base64,${message})`;
            } else if (intentType === "text-to-image2") {
                imageMarkdown = `![](${message})`;
            } else if (intentType === "text-to-image-v3") {
                imageMarkdown = `![](data:image/webp;base64,${message})`;
            }
            const inferredQuery = inferredQueries?.[0];
            if (inferredQuery) {
                imageMarkdown += `\n\n**Inferred Query**:\n\n${inferredQuery}`;
            }
            return imageMarkdown;
        }

        //handler function for posting feedback data to endpoint
        function sendFeedback(_uquery="", _kquery="", _sentiment="") {
            const uquery = _uquery;
            const kquery = _kquery;
            const sentiment = _sentiment;
            fetch('/api/chat/feedback', {
                method: 'POST',
                headers: {
                'Content-Type': 'application/json'
                },
                body: JSON.stringify({uquery: uquery, kquery: kquery, sentiment: sentiment})
            })
            .then(response => response.json())
        }

        function formatHTMLMessage(message, raw=false, willReplace=true, userQuery) {
            var md = window.markdownit();
            let newHTML = message;

            // Replace LaTeX delimiters with placeholders
            newHTML = newHTML.replace(/\\\(/g, 'LEFTPAREN').replace(/\\\)/g, 'RIGHTPAREN')
                             .replace(/\\\[/g, 'LEFTBRACKET').replace(/\\\]/g, 'RIGHTBRACKET');

            // Remove any text between <s>[INST] and </s> tags. These are spurious instructions for the AI chat model.
            newHTML = newHTML.replace(/<s>\[INST\].+(<\/s>)?/g, '');

            // Customize the rendering of images
            md.renderer.rules.image = function(tokens, idx, options, env, self) {
                let token = tokens[idx];

                // Add class="text-to-image" to images
                token.attrPush(['class', 'text-to-image']);

                // Use the default renderer to render image markdown format
                return self.renderToken(tokens, idx, options);
            };

            // Render markdown
            newHTML = raw ? newHTML : md.render(newHTML);

            // Replace placeholders with LaTeX delimiters
            newHTML = newHTML.replace(/LEFTPAREN/g, '\\(').replace(/RIGHTPAREN/g, '\\)')
                             .replace(/LEFTBRACKET/g, '\\[').replace(/RIGHTBRACKET/g, '\\]');

            // Set rendered markdown to HTML DOM element
            let element = document.createElement('div');
            element.innerHTML = newHTML;
            element.className = "chat-message-text-response";

            // Add a copy button to each chat message, if it doesn't already exist
            if (willReplace === true) {
                let copyButton = document.createElement('button');
                copyButton.classList.add("copy-button");
                copyButton.title = "Copy Message";
                let copyIcon = document.createElement("img");
                copyIcon.src = "/static/assets/icons/copy-button.svg";
                copyIcon.classList.add("copy-icon");
                copyButton.appendChild(copyIcon);
                copyButton.addEventListener('click', createCopyParentText(message));

                //create thumbs-up button
                let thumbsUpButton = document.createElement('button');
                thumbsUpButton.className = 'thumbs-up-button';
                let thumbsUpIcon = document.createElement("img");
                thumbsUpIcon.src = "/static/assets/icons/thumbs-up-svgrepo-com.svg";
                thumbsUpIcon.classList.add("thumbs-up-icon");
                thumbsUpButton.appendChild(thumbsUpIcon);
                thumbsUpButton.onclick = function() {
                    khojQuery = newHTML;
                    thumbsUpIcon.src = "/static/assets/icons/confirm-icon.svg";
                    sendFeedback(userQuery ,khojQuery, "Good Response");
                };

                // Create thumbs-down button
                let thumbsDownButton = document.createElement('button');
                thumbsDownButton.className = 'thumbs-down-button';
                let thumbsDownIcon = document.createElement("img");
                thumbsDownIcon.src = "/static/assets/icons/thumbs-down-svgrepo-com.svg";
                thumbsDownIcon.classList.add("thumbs-down-icon");
                thumbsDownButton.appendChild(thumbsDownIcon);
                thumbsDownButton.onclick = function() {
                    khojQuery = newHTML;
                    thumbsDownIcon.src = "/static/assets/icons/confirm-icon.svg";
                    sendFeedback(userQuery, khojQuery, "Bad Response");
                };

                // Append buttons to parent element
                element.append(copyButton, thumbsDownButton, thumbsUpButton);
            }

            renderMathInElement(element, {
                // customised options
                // • auto-render specific keys, e.g.:
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '\\(', right: '\\)', display: false},
                    {left: '\\[', right: '\\]', display: true}
                ],
                // • rendering keys, e.g.:
                throwOnError : false
            });

            // Get any elements with a class that starts with "language"
            let codeBlockElements = element.querySelectorAll('[class^="language-"]');
            // For each element, add a parent div with the class "programmatic-output"
            codeBlockElements.forEach((codeElement) => {
                // Create the parent div
                let parentDiv = document.createElement('div');
                parentDiv.classList.add("programmatic-output");
                // Add the parent div before the code element
                codeElement.parentNode.insertBefore(parentDiv, codeElement);
                // Move the code element into the parent div
                parentDiv.appendChild(codeElement);
                // Add a copy button to each code block, if it doesn't already exist
                if (willReplace === true) {
                    let copyButton = document.createElement('button');
                    copyButton.classList.add("copy-button");
                    copyButton.title = "Copy Code";
                    let copyIcon = document.createElement("img");
                    copyIcon.src = "/static/assets/icons/copy-button.svg";
                    copyIcon.classList.add("copy-icon");
                    copyButton.appendChild(copyIcon);
                    copyButton.addEventListener('click', copyParentText);
                    codeElement.prepend(copyButton);
                }
            });

            // Get all code elements that have no class.
            let codeElements = element.querySelectorAll('code:not([class])');
            codeElements.forEach((codeElement) => {
                // Add the class "chat-response" to each element
                codeElement.classList.add("chat-response");
            });

            let anchorElements = element.querySelectorAll('a');
            anchorElements.forEach((anchorElement) => {
                // Add the class "inline-chat-link" to each element
                anchorElement.classList.add("inline-chat-link");
            });

            return element
        }

        function createReferenceSection(references) {
            let referenceSection = document.createElement('div');
            referenceSection.classList.add("reference-section");
            referenceSection.classList.add("collapsed");

            let numReferences = 0;

            if (references.hasOwnProperty("notes")) {
                numReferences += references["notes"].length;

                references["notes"].forEach((reference, index) => {
                    let polishedReference = generateReference(reference, index);
                    referenceSection.appendChild(polishedReference);
                });
            }
            if (references.hasOwnProperty("online")) {
                numReferences += processOnlineReferences(referenceSection, references["online"]);
            }

            let referenceExpandButton = document.createElement('button');
            referenceExpandButton.classList.add("reference-expand-button");
            referenceExpandButton.innerHTML = numReferences == 1 ? "1 reference" : `${numReferences} references`;

            referenceExpandButton.addEventListener('click', function() {
                if (referenceSection.classList.contains("collapsed")) {
                    referenceSection.classList.remove("collapsed");
                    referenceSection.classList.add("expanded");
                } else {
                    referenceSection.classList.add("collapsed");
                    referenceSection.classList.remove("expanded");
                }
            });

            let referencesDiv = document.createElement('div');
            referencesDiv.classList.add("references");
            referencesDiv.appendChild(referenceExpandButton);
            referencesDiv.appendChild(referenceSection);

            return referencesDiv;
        }

        async function chat() {
            if (websocket) {
                sendMessageViaWebSocket();
                return;
            }

            let query = document.getElementById("chat-input").value.trim();
            let resultsCount = localStorage.getItem("khojResultsCount") || 5;
            console.log(`Query: ${query}`);

            // Short circuit on empty query
            if (query.length === 0)
                return;

            // Add message by user to chat body
            renderMessage(query, "you");
            document.getElementById("chat-input").value = "";
            autoResize();
            document.getElementById("chat-input").setAttribute("disabled", "disabled");
            let chat_body = document.getElementById("chat-body");

            let conversationID = chat_body.dataset.conversationId;

            if (!conversationID) {
                let response = await fetch('/api/chat/sessions', { method: "POST" });
                let data = await response.json();
                conversationID = data.conversation_id;
                chat_body.dataset.conversationId = conversationID;
                refreshChatSessionsPanel();
            }

            let new_response = document.createElement("div");
            new_response.classList.add("chat-message", "khoj");
            new_response.attributes["data-meta"] = "🏮 Khoj at " + formatDate(new Date());
            chat_body.appendChild(new_response);

            let newResponseText = document.createElement("div");
            newResponseText.classList.add("chat-message-text", "khoj");
            new_response.appendChild(newResponseText);

            // Temporary status message to indicate that Khoj is thinking
            let loadingEllipsis = createLoadingEllipse();

            newResponseText.appendChild(loadingEllipsis);
            document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;

            let chatTooltip = document.getElementById("chat-tooltip");
            chatTooltip.style.display = "none";

            let chatInput = document.getElementById("chat-input");
            chatInput.classList.remove("option-enabled");

            // Generate backend API URL to execute query
            let url = `/api/chat?q=${encodeURIComponent(query)}&n=${resultsCount}&client=web&stream=true&conversation_id=${conversationID}&region=${region}&city=${city}&country=${countryName}&timezone=${timezone}`;

            // Call specified Khoj API
            let response = await fetch(url);
            let rawResponse = "";
            let references = null;
            const contentType = response.headers.get("content-type");

            if (contentType === "application/json") {
                // Handle JSON response
                try {
                    const responseAsJson = await response.json();
                    if (responseAsJson.image || responseAsJson.detail) {
                        ({rawResponse, references } = handleImageResponse(responseAsJson, rawResponse));
                    } else {
                        rawResponse = responseAsJson.response;
                    }
                } catch (error) {
                    // If the chunk is not a JSON object, just display it as is
                    rawResponse += chunk;
                } finally {
                    addMessageToChatBody(rawResponse, newResponseText, references);
                }
            } else {
                // Handle streamed response of type text/event-stream or text/plain
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let references = {};

                readStream();

                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            // Append any references after all the data has been streamed
                            finalizeChatBodyResponse(references, newResponseText);
                            return;
                        }

                        // Decode message chunk from stream
                        const chunk = decoder.decode(value, { stream: true });

                        if (chunk.includes("### compiled references:")) {
                            ({ rawResponse, references } = handleCompiledReferences(newResponseText, chunk, references, rawResponse));
                            readStream();
                        } else {
                            // If the chunk is not a JSON object, just display it as is
                            rawResponse += chunk;
                            handleStreamResponse(newResponseText, rawResponse, query, loadingEllipsis);
                            readStream();
                        }
                    });

                    // Scroll to bottom of chat window as chat response is streamed
                    document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;
                };
            }
        };

        function createLoadingEllipse() {
            // Temporary status message to indicate that Khoj is thinking
            let loadingEllipsis = document.createElement("div");
            loadingEllipsis.classList.add("lds-ellipsis");

            let firstEllipsis = document.createElement("div");
            firstEllipsis.classList.add("lds-ellipsis-item");

            let secondEllipsis = document.createElement("div");
            secondEllipsis.classList.add("lds-ellipsis-item");

            let thirdEllipsis = document.createElement("div");
            thirdEllipsis.classList.add("lds-ellipsis-item");

            let fourthEllipsis = document.createElement("div");
            fourthEllipsis.classList.add("lds-ellipsis-item");

            loadingEllipsis.appendChild(firstEllipsis);
            loadingEllipsis.appendChild(secondEllipsis);
            loadingEllipsis.appendChild(thirdEllipsis);
            loadingEllipsis.appendChild(fourthEllipsis);

            return loadingEllipsis;
        }

        function handleStreamResponse(newResponseElement, rawResponse, rawQuery, loadingEllipsis, replace=true) {
            if (newResponseElement.getElementsByClassName("lds-ellipsis").length > 0 && loadingEllipsis) {
                newResponseElement.removeChild(loadingEllipsis);
            }
            if (replace) {
                newResponseElement.innerHTML = "";
            }
            newResponseElement.appendChild(formatHTMLMessage(rawResponse, false, replace, rawQuery));
            document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;
        }

        function handleCompiledReferences(rawResponseElement, chunk, references, rawResponse) {
            const additionalResponse = chunk.split("### compiled references:")[0];
            rawResponse += additionalResponse;
            rawResponseElement.innerHTML = "";
            rawResponseElement.appendChild(formatHTMLMessage(rawResponse));

            const rawReference = chunk.split("### compiled references:")[1];
            const rawReferenceAsJson = JSON.parse(rawReference);
            if (rawReferenceAsJson instanceof Array) {
                references["notes"] = rawReferenceAsJson;
            } else if (typeof rawReferenceAsJson === "object" && rawReferenceAsJson !== null) {
                references["online"] = rawReferenceAsJson;
            }
            return { rawResponse, references };
        }

        function handleImageResponse(imageJson, rawResponse) {
            if (imageJson.image) {
                const inferredQuery = imageJson.inferredQueries?.[0] ?? "generated image";

                // If response has image field, response is a generated image.
                if (imageJson.intentType === "text-to-image") {
                    rawResponse += `![generated_image](data:image/png;base64,${imageJson.image})`;
                } else if (imageJson.intentType === "text-to-image2") {
                    rawResponse += `![generated_image](${imageJson.image})`;
                } else if (imageJson.intentType === "text-to-image-v3") {
                    rawResponse = `![](data:image/webp;base64,${imageJson.image})`;
                }
                if (inferredQuery) {
                    rawResponse += `\n\n**Inferred Query**:\n\n${inferredQuery}`;
                }
            }
            let references = {};
            if (imageJson.context && imageJson.context.length > 0) {
                const rawReferenceAsJson = imageJson.context;
                if (rawReferenceAsJson instanceof Array) {
                    references["notes"] = rawReferenceAsJson;
                } else if (typeof rawReferenceAsJson === "object" && rawReferenceAsJson !== null) {
                    references["online"] = rawReferenceAsJson;
                }
            }
            if (imageJson.detail) {
                // If response has detail field, response is an error message.
                rawResponse += imageJson.detail;
            }
            return { rawResponse, references };
        }

        function addMessageToChatBody(rawResponse, newResponseElement, references) {
            newResponseElement.innerHTML = "";
            newResponseElement.appendChild(formatHTMLMessage(rawResponse));

            finalizeChatBodyResponse(references, newResponseElement);
        }

        function finalizeChatBodyResponse(references, newResponseElement) {
            if (references != null && Object.keys(references).length > 0) {
                newResponseElement.appendChild(createReferenceSection(references));
            }
            document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;
            document.getElementById("chat-input").removeAttribute("disabled");
        }

        function incrementalChat(event) {
            if (!event.shiftKey && event.key === 'Enter') {
                event.preventDefault();
                chat();
            }
        }

        function fillCommandInPrompt(command) {
            let chatTooltip = document.getElementById("chat-tooltip");
            chatTooltip.style.display = "none";

            let chatInput = document.getElementById("chat-input");
            chatInput.value = "/" + command + " ";
            chatInput.classList.add("option-enabled");
            chatInput.focus();
        }

        function onChatInput() {
            let chatInput = document.getElementById("chat-input");
            chatInput.value = chatInput.value.trimStart();

            let questionStarterSuggestions = document.getElementById("question-starters");
            questionStarterSuggestions.innerHTML = "";
            questionStarterSuggestions.style.display = "none";

            if (chatInput.value.startsWith("/") && chatInput.value.split(" ").length === 1) {
                let chatTooltip = document.getElementById("chat-tooltip");
                chatTooltip.style.display = "block";
                let helpText = "<div>";
                const command = chatInput.value.split(" ")[0].substring(1);
                for (let key in chatOptions) {
                    if (!!!command || key.startsWith(command)) {
                        helpText += `<div class="helpoption" onclick="fillCommandInPrompt('${key}')"><b>/${key}</b>: ${chatOptions[key]}</div>`;
                    }
                }
                chatTooltip.innerHTML = helpText;
            } else if (chatInput.value.startsWith("/")) {
                const firstWord = chatInput.value.split(" ")[0];
                if (firstWord.substring(1) in chatOptions) {
                    chatInput.classList.add("option-enabled");
                } else {
                    chatInput.classList.remove("option-enabled");
                }
                let chatTooltip = document.getElementById("chat-tooltip");
                chatTooltip.style.display = "none";
            } else {
                let chatTooltip = document.getElementById("chat-tooltip");
                chatTooltip.style.display = "none";
                chatInput.classList.remove("option-enabled");
            }

            autoResize();
        }

        function autoResize() {
            const textarea = document.getElementById('chat-input');
            const scrollTop = textarea.scrollTop;
            textarea.style.height = '0';
            const scrollHeight = textarea.scrollHeight + 8;  // +8 accounts for padding
            textarea.style.height = Math.min(scrollHeight, 200) + 'px';
            textarea.scrollTop = scrollTop;
            document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;
        }

        function openFileBrowser() {
            event.preventDefault();
            var overlayText = document.getElementById("dropzone-overlay");
            var dropzone = document.getElementById('chat-body');

            if (overlayText == null) {
                dropzone.classList.add('dragover');
                var overlayText = document.createElement("div");
                overlayText.innerHTML = "Select a file or drag + drop it here to share it with Khoj";
                overlayText.className = "dropzone-overlay";
                overlayText.id = "dropzone-overlay";
                dropzone.appendChild(overlayText);
            }

            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.addEventListener('change', function() {
                const selectedFile = fileInput.files[0];
                uploadDataForIndexing(selectedFile);
            });

            // Remove overlay text after file input is closed
            fileInput.addEventListener('blur', function() {
                dropzone.classList.remove('dragover');
                var overlayText = document.getElementById("dropzone-overlay");
                if (overlayText != null) {
                    overlayText.remove();
                }
            });

            // Remove overlay text if file input is cancelled
            fileInput.addEventListener('cancel', function() {
                dropzone.classList.remove('dragover');
                var overlayText = document.getElementById("dropzone-overlay");
                if (overlayText != null) {
                    overlayText.remove();
                }
            });

            fileInput.click();
        }

        function uploadDataForIndexing(file) {
            var dropzone = document.getElementById('chat-body');

            if (!file || (!allowedExtensions.includes(file.type) && !allowedFileEndings.includes(file.name.split('.').pop()))) {
                dropzone.classList.remove('dragover');
                if (file) {
                    alert("Sorry, that file type is not yet supported");
                }
                var overlayText = document.getElementById("dropzone-overlay");
                if (overlayText != null) {
                    overlayText.remove();
                }
                return;
            }

            const fileName = file.name;
            var fileContents = null;

            var reader = new FileReader();
            const formData = new FormData();


            var overlayText = document.getElementById("dropzone-overlay");
            if (overlayText != null) {
                // Display loading spinner
                var loadingSpinner = document.createElement("div");
                overlayText.innerHTML = "Uploading file for indexing";
                loadingSpinner.className = "spinner";
                overlayText.appendChild(loadingSpinner);
            }

            reader.onload = function (event) {
                fileContents = event.target.result;
                let fileType = file.type;
                if (fileType === "") {
                    if (fileName.split('.').pop() === "org") {
                        fileType = "text/org";
                    } else if (fileName.split('.').pop() === "md") {
                        fileType = "text/markdown";
                    } else if (fileName.split('.').pop() === "txt") {
                        fileType = "text/plain";
                    } else if (fileName.split('.').pop() === "html") {
                        fileType = "text/html";
                    } else if (fileName.split('.').pop() === "pdf") {
                        fileType = "application/pdf";
                    }
                }

                let fileObj = new Blob([fileContents], { type: fileType });
                formData.append("files", fileObj, file.name);
                console.log(formData);

                fetch("/api/v1/index/update?force=false&client=web", {
                    method: "POST",
                    body: formData,
                })
                    .then((data) => {
                        console.log(data);
                        dropzone.classList.remove('dragover');
                        var overlayText = document.getElementById("dropzone-overlay");
                        if (overlayText != null) {
                            overlayText.remove();
                        }
                        // Display indexing success message
                        flashStatusInChatInput("✅ File indexed successfully");


                    })
                    .catch((error) => {
                        console.log(error);
                        dropzone.classList.remove('dragover');
                        var overlayText = document.getElementById("dropzone-overlay");
                        if (overlayText != null) {
                            overlayText.remove();
                        }
                        // Display indexing failure message
                        flashStatusInChatInput("⛔️ Failed to upload file for indexing");
                    });
            };

            reader.readAsArrayBuffer(file);
        }

        function setupDropZone() {
            var dropzone = document.getElementById('chat-body');

            dropzone.ondragover = function(event) {
                event.preventDefault();
                this.classList.add('dragover');
                var overlayText = document.getElementById("dropzone-overlay");
                console.log("ondragover triggered");

                if (overlayText == null) {
                    var overlayText = document.createElement("div");
                    overlayText.innerHTML = "Drop file to share it with Khoj";
                    overlayText.className = "dropzone-overlay";
                    overlayText.id = "dropzone-overlay";
                    this.appendChild(overlayText);
                }
            };

            dropzone.ondragleave = function(event) {
                event.preventDefault();
                this.classList.remove('dragover');
                console.log("ondragleave triggered");
                var overlayText = document.getElementById("dropzone-overlay");
                if (overlayText != null) {
                    overlayText.remove();
                }
            };

            dropzone.ondrop = function(event) {
                event.preventDefault();

                var file = event.dataTransfer.files[0];
                uploadDataForIndexing(file);
            };
        }

        window.onload = loadChat;

        function setupWebSocket() {
            let chatBody = document.getElementById("chat-body");
            let wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            let webSocketUrl = `${wsProtocol}//${window.location.host}/api/chat/ws`;

            if (waitingForLocation) {
                console.debug("Waiting for location data to be fetched. Will setup WebSocket once location data is available.");
                return;
            }

            websocketState = {
                newResponseTextEl: null,
                newResponseEl: null,
                loadingEllipsis: null,
                references: {},
                rawResponse: "",
                rawQuery: "",
            }

            if (chatBody.dataset.conversationId) {
                webSocketUrl += `?conversation_id=${chatBody.dataset.conversationId}`;
                webSocketUrl += (!!region && !!city && !!countryName) && !!timezone ? `&region=${region}&city=${city}&country=${countryName}&timezone=${timezone}` : '';

                websocket = new WebSocket(webSocketUrl);
                websocket.onmessage = function(event) {

                    // Get the last element in the chat-body
                    let chunk = event.data;
                    if (chunk == "start_llm_response") {
                        console.log("Started streaming", new Date());
                    } else if(chunk == "end_llm_response") {
                        console.log("Stopped streaming", new Date());
                        // Append any references after all the data has been streamed
                        finalizeChatBodyResponse(websocketState.references, websocketState.newResponseTextEl);

                        const liveQuery = websocketState.rawQuery;
                        // Reset variables
                        websocketState = {
                            newResponseTextEl: null,
                            newResponseEl: null,
                            loadingEllipsis: null,
                            references: {},
                            rawResponse: "",
                            rawQuery: liveQuery,
                        }
                    } else {
                        try {
                            if (chunk.includes("application/json"))
                            {
                                chunk = JSON.parse(chunk);
                            }
                        } catch (error) {
                            // If the chunk is not a JSON object, continue.
                        }

                        const contentType = chunk["content-type"]

                        if (contentType === "application/json") {
                            // Handle JSON response
                            try {
                                if (chunk.image || chunk.detail) {
                                    ({rawResponse, references } = handleImageResponse(chunk, websocketState.rawResponse));
                                    websocketState.rawResponse = rawResponse;
                                    websocketState.references = references;
                                } else if (chunk.type == "status") {
                                    handleStreamResponse(websocketState.newResponseTextEl, chunk.message, websocketState.rawQuery, null, false);
                                } else if (chunk.type == "rate_limit") {
                                    handleStreamResponse(websocketState.newResponseTextEl, chunk.message, websocketState.rawQuery, websocketState.loadingEllipsis, true);
                                } else {
                                    rawResponse = chunk.response;
                                }
                            } catch (error) {
                                // If the chunk is not a JSON object, just display it as is
                                websocketState.rawResponse += chunk;
                            } finally {
                                if (chunk.type != "status" && chunk.type != "rate_limit") {
                                    addMessageToChatBody(websocketState.rawResponse, websocketState.newResponseTextEl, websocketState.references);
                                }
                            }
                        } else {

                            // Handle streamed response of type text/event-stream or text/plain
                            if (chunk && chunk.includes("### compiled references:")) {
                                ({ rawResponse, references } = handleCompiledReferences(websocketState.newResponseTextEl, chunk, websocketState.references, websocketState.rawResponse));
                                websocketState.rawResponse = rawResponse;
                                websocketState.references = references;
                            } else {
                                // If the chunk is not a JSON object, just display it as is
                                websocketState.rawResponse += chunk;
                                if (websocketState.newResponseTextEl) {
                                    handleStreamResponse(websocketState.newResponseTextEl, websocketState.rawResponse, websocketState.rawQuery, websocketState.loadingEllipsis);
                                }
                            }

                            // Scroll to bottom of chat window as chat response is streamed
                            document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;
                        };
                    }
                }
            };
            websocket.onclose = function(event) {
                websocket = null;
                console.log("WebSocket is closed now.");
                let statusDotIcon = document.getElementById("connection-status-icon");
                statusDotIcon.style.backgroundColor = "red";
                let statusDotText = document.getElementById("connection-status-text");
                statusDotText.style.marginTop = "5px";
                statusDotText.innerHTML = '<button onclick="setupWebSocket()">Reconnect to Server</button>';
            }
            websocket.onerror = function(event) {
                console.log("WebSocket error observed:", event);
            }

            websocket.onopen = function(event) {
                console.log("WebSocket is open now.")
                let statusDotIcon = document.getElementById("connection-status-icon");
                statusDotIcon.style.backgroundColor = "green";
                let statusDotText = document.getElementById("connection-status-text");
                statusDotText.style.marginTop = "10px";
                statusDotText.textContent = "Connected to Server";
            }
        }

        function sendMessageViaWebSocket() {
            let chatBody = document.getElementById("chat-body");

            var query = document.getElementById("chat-input").value.trim();
            console.log(`Query: ${query}`);

            // Add message by user to chat body
            renderMessage(query, "you");
            document.getElementById("chat-input").value = "";
            autoResize();
            document.getElementById("chat-input").setAttribute("disabled", "disabled");

            let newResponseEl = document.createElement("div");
            newResponseEl.classList.add("chat-message", "khoj");
            newResponseEl.attributes["data-meta"] = "🏮 Khoj at " + formatDate(new Date());
            chatBody.appendChild(newResponseEl);

            let newResponseTextEl = document.createElement("div");
            newResponseTextEl.classList.add("chat-message-text", "khoj");
            newResponseEl.appendChild(newResponseTextEl);

            // Temporary status message to indicate that Khoj is thinking
            let loadingEllipsis = createLoadingEllipse();

            newResponseTextEl.appendChild(loadingEllipsis);
            document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;

            let chatTooltip = document.getElementById("chat-tooltip");
            chatTooltip.style.display = "none";

            let chatInput = document.getElementById("chat-input");
            chatInput.classList.remove("option-enabled");

            // Call specified Khoj API
            websocket.send(query);
            let rawResponse = "";
            let references = {};

            websocketState = {
                newResponseTextEl,
                newResponseEl,
                loadingEllipsis,
                references,
                rawResponse,
                rawQuery: query,
            }
        }

        function loadChat() {
            let chatBody = document.getElementById("chat-body");
            chatBody.innerHTML = "";
            chatBody.classList.add("relative-position");
            let chatHistoryUrl = `/api/chat/history?client=web`;
            if (chatBody.dataset.conversationId) {
                chatHistoryUrl += `&conversation_id=${chatBody.dataset.conversationId}`;
                setupWebSocket();
            }

            if (window.screen.width < 700) {
                handleCollapseSidePanel();
            }

            // Create loading screen and add it to chat-body
            let loadingScreen = document.createElement('div');
            loadingScreen.classList.add("loading-spinner");
            let yellowOrb = document.createElement('div');
            loadingScreen.appendChild(yellowOrb);
            chatBody.appendChild(loadingScreen);

            // Get the most recent 10 chat messages from conversation history
            fetch(`${chatHistoryUrl}&n=10`, { method: "GET" })
                .then(response => response.json())
                .then(data => {
                    if (data.detail) {
                        // If the server returns a 500 error with detail, render a setup hint.
                        let setupMsg = "Hi 👋🏾, to start chatting add available chat models options via <a class='inline-chat-link' href='/server/admin'>the Django Admin panel</a> on the Server";
                        renderMessage(setupMsg, "khoj", null, null, true);

                        // Disable chat input field and update placeholder text
                        document.getElementById("chat-input").setAttribute("disabled", "disabled");
                        document.getElementById("chat-input").setAttribute("placeholder", "Configure Khoj to enable chat");
                    } else if (data.status != "ok") {
                        throw new Error(data.message);
                    } else {
                        // Set welcome message on load
                        renderMessage(welcome_message, "khoj");
                    }
                    return data.response;
                })
                .then(response => {
                    // Render conversation history, if any
                    let chatBody = document.getElementById("chat-body");
                    chatBody.dataset.conversationId = response.conversation_id;
                    setupWebSocket();
                    chatBody.dataset.conversationTitle = response.slug || `New conversation 🌱`;

                    let agentMetadata = response.agent;
                    if (agentMetadata) {
                        chatBody.innerHTML = "";
                        let agentName = agentMetadata.name;
                        let agentAvatar = agentMetadata.avatar;
                        let agentOwnedByUser = agentMetadata.isCreator;

                        let agentAvatarElement = document.getElementById("agent-avatar");
                        let agentNameElement = document.getElementById("agent-name");

                        let agentLinkElement = document.getElementById("agent-link");

                        agentAvatarElement.src = agentAvatar;
                        agentNameElement.textContent = agentName;
                        agentLinkElement.setAttribute("href", `/agent/${agentMetadata.slug}`);
                        renderMessage(`Hello! I'm [${agentName}](/agent/${agentMetadata.slug}). I can:
- 🧠 Answer general knowledge questions
- 🔎 Get real-time answers from the internet
- 📜 Find relevant info in your notes & documents
- 💡 Be a sounding board for your ideas
- 🌄 Generate images based on your context
- 🎙️ Hear you talk (use the mic by the input box to say your message out loud)
- 📚 Understand files you drag & drop here
- 👩🏾‍🚀 Be tuned to your conversation needs via [agents](./agents)

Get the Khoj [Desktop](https://khoj.dev/downloads), [Obsidian](https://docs.khoj.dev/clients/obsidian#setup), or [Emacs](https://docs.khoj.dev/clients/emacs#setup) app to keep your files in sync. You can manage all the files you've shared with me at any time by going to [your settings](/config/content-source/computer/).

To get started, just start typing below. You can also type / to see a list of commands.

**What's on your mind today?**
                        `, "khoj")

                        if (agentOwnedByUser) {
                            let agentOwnedByUserElement = document.getElementById("agent-owned-by-user");
                            agentOwnedByUserElement.style.display = "block";
                        }

                        let agentMetadataElement = document.getElementById("agent-metadata");
                        agentMetadataElement.style.display = "block";
                    } else {
                        let agentMetadataElement = document.getElementById("agent-metadata");
                        agentMetadataElement.style.display = "none";
                    }

                    // Create a new IntersectionObserver
                    let fetchRemainingMessagesObserver = new IntersectionObserver((entries, observer) => {
                        entries.forEach(entry => {
                            // If the element is in the viewport, fetch the remaining message and unobserve the element
                            if (entry.isIntersecting) {
                                fetchRemainingChatMessages(chatHistoryUrl);
                                observer.unobserve(entry.target);
                            }
                        });
                    }, {rootMargin: '0px 0px 0px 0px'});

                    const fullChatLog = response.chat || [];
                    fullChatLog.forEach((chat_log, index) => {
                        // Render the last 10 messages immediately
                        if (chat_log.message != null) {
                            let messageElement = renderMessageWithReference(
                                chat_log.message,
                                chat_log.by,
                                chat_log.context,
                                new Date(chat_log.created + "Z"),
                                chat_log.onlineContext,
                                chat_log.intent?.type,
                                chat_log.intent?.["inferred-queries"],
                                chat_log.intent?.query);
                            chatBody.appendChild(messageElement);

                            // When the 4th oldest message is within viewing distance (~60% scroll up)
                            // Fetch the remaining chat messages
                            if (index === 4) {
                                fetchRemainingMessagesObserver.observe(messageElement);
                            }
                        }
                        loadingScreen.style.height = chatBody.scrollHeight + 'px';
                    });

                    // Scroll to bottom of chat-body element
                    chatBody.scrollTop = chatBody.scrollHeight;

                    // Set height of chat-body element to the height of the chat-body-wrapper
                    let chatBodyWrapper = document.getElementById("chat-body-wrapper");
                    let chatBodyWrapperHeight = chatBodyWrapper.clientHeight;
                    chatBody.style.height = chatBodyWrapperHeight;

                    // Add fade out animation to loading screen and remove it after the animation ends
                    setTimeout(() => {
                        loadingScreen.remove();
                        chatBody.classList.remove("relative-position");
                        setupDropZone();
                    }, 500);

                })
                .catch(err => {
                    console.log(err);
                    return;
                });

            refreshChatSessionsPanel();

            fetch('/api/chat/options')
                .then(response => response.json())
                .then(data => {
                    // Render chat options, if any
                    if (data) {
                        chatOptions = data;
                    }
                })
                .catch(err => {
                    return;
                });

            fetch('/api/chat/starters')
                .then(response => response.json())
                .then(data => {
                    // Render chat options, if any
                    if (data.length > 0) {
                        let questionStarterSuggestions = document.getElementById("question-starters");
                        questionStarterSuggestions.innerHTML = "";
                        data.forEach((questionStarter) => {
                            let questionStarterButton = document.createElement('button');
                            questionStarterButton.innerHTML = questionStarter;
                            questionStarterButton.classList.add("question-starter");
                            questionStarterButton.addEventListener('click', function() {
                                questionStarterSuggestions.style.display = "none";
                                document.getElementById("chat-input").value = questionStarter;
                                chat();
                            });
                            questionStarterSuggestions.appendChild(questionStarterButton);
                        });
                        questionStarterSuggestions.style.display = "grid";
                    }
                })
                .catch(err => {
                    return;
                });

            // Fill query field with value passed in URL query parameters, if any.
            var query_via_url = new URLSearchParams(window.location.search).get("q");
            if (query_via_url) {
                document.getElementById("chat-input").value = query_via_url;
                chat();
            }

        }

        function fetchRemainingChatMessages(chatHistoryUrl) {
            // Create a new IntersectionObserver
            let observer = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    // If the element is in the viewport, render the message and unobserve the element
                    if (entry.isIntersecting) {
                        let chat_log = entry.target.chat_log;
                        let messageElement = renderMessageWithReference(
                            chat_log.message,
                            chat_log.by,
                            chat_log.context,
                            new Date(chat_log.created + "Z"),
                            chat_log.onlineContext,
                            chat_log.intent?.type,
                            chat_log.intent?.["inferred-queries"],
                            chat_log.intent?.query
                        );
                        entry.target.replaceWith(messageElement);

                        // Remove the observer after the element has been rendered
                        observer.unobserve(entry.target);
                    }
                });
            }, {rootMargin: '0px 0px 200px 0px'});  // Trigger when the element is within 200px of the viewport

            // Fetch remaining chat messages from conversation history
            fetch(`${chatHistoryUrl}&n=-10`, { method: "GET" })
                .then(response => response.json())
                .then(data => {
                    if (data.status != "ok") {
                        throw new Error(data.message);
                    }
                    return data.response;
                })
                .then(response => {
                    const fullChatLog = response.chat || [];
                    let chatBody = document.getElementById("chat-body");
                    fullChatLog
                    .reverse()
                    .forEach(chat_log => {
                        if (chat_log.message != null) {
                            // Create a new element for each chat log
                            let placeholder = document.createElement('div');
                            placeholder.chat_log = chat_log;

                            // Insert the message placeholder as the first child of chat body after the welcome message
                            chatBody.insertBefore(placeholder, chatBody.firstChild.nextSibling);

                            // Observe the element
                            placeholder.style.height = "20px";
                            observer.observe(placeholder);
                        }
                    });
                })
                .catch(err => {
                    console.log(err);
                    return;
                });
        }

        function flashStatusInChatInput(message) {
            // Get chat input element and original placeholder
            let chatInput = document.getElementById("chat-input");
            let originalPlaceholder = chatInput.placeholder;
            // Set placeholder to message
            chatInput.placeholder = message;
            // Reset placeholder after 2 seconds
            setTimeout(() => {
                chatInput.placeholder = originalPlaceholder;
            }, 2000);
        }

        function createNewConversation() {
            // Create a modal that appears in the middle of the entire screen. It should have a form to create a new conversation.
            let modal = document.createElement('div');
            modal.classList.add("modal");
            modal.id = "new-conversation-modal";
            let modalContent = document.createElement('div');
            modalContent.classList.add("modal-content");
            let modalHeader = document.createElement('div');
            modalHeader.classList.add("modal-header");
            let modalTitle = document.createElement('h2');
            modalTitle.textContent = "New Conversation";
            let modalCloseButton = document.createElement('button');
            modalCloseButton.classList.add("modal-close-button");
            modalCloseButton.innerHTML = "&times;";
            modalCloseButton.addEventListener('click', function() {
                modal.remove();
            });
            modalHeader.appendChild(modalTitle);
            modalHeader.appendChild(modalCloseButton);
            modalContent.appendChild(modalHeader);
            let modalBody = document.createElement('div');
            modalBody.classList.add("modal-body");

            let agentDropDownPicker = document.createElement('select');
            agentDropDownPicker.setAttribute("id", "agent-dropdown-picker");
            agentDropDownPicker.setAttribute("name", "agent-dropdown-picker");

            let agentDropDownLabel = document.createElement('label');
            agentDropDownLabel.setAttribute("for", "agent-dropdown-picker");
            agentDropDownLabel.textContent = "Who do you want to talk to?";

            fetch('/api/agents')
                .then(response => response.json())
                .then(data => {
                    if (data.length > 0) {
                        data.forEach((agent) => {
                            let agentOption = document.createElement('option');
                            agentOption.setAttribute("value", agent.slug);
                            agentOption.textContent = agent.name;
                            agentDropDownPicker.appendChild(agentOption);
                        });
                    }
                })
                .catch(err => {
                    return;
                });

            let seeAllAgentsLink = document.createElement('a');
            seeAllAgentsLink.setAttribute("href", "/agents");
            seeAllAgentsLink.setAttribute("target", "_blank");
            seeAllAgentsLink.textContent = "See all agents";

            let newConversationSubmitButton = document.createElement('button');
            newConversationSubmitButton.setAttribute("type", "submit");
            newConversationSubmitButton.textContent = "Go";
            newConversationSubmitButton.id = "new-conversation-submit-button";

            newConversationSubmitButton.addEventListener('click', function(event) {
                event.preventDefault();
                let agentSlug = agentDropDownPicker.value;
                let createURL = `/api/chat/sessions?client=web&agent_slug=${agentSlug}`;
                let chatBody = document.getElementById("chat-body");
                fetch(createURL, { method: "POST" })
                    .then(response => response.json())
                    .then(data => {
                        chatBody.dataset.conversationId = data.conversation_id;
                        modal.remove();
                        loadChat();
                    })
                    .catch(err => {
                        return;
                    });
            });

            let closeButton = document.createElement('button');
            closeButton.id = "close-button";
            closeButton.innerHTML = "Close";
            closeButton.classList.add("close-button");
            closeButton.addEventListener('click', function() {
                modal.remove();
            });

            modalBody.appendChild(agentDropDownLabel);
            modalBody.appendChild(agentDropDownPicker);
            modalBody.appendChild(seeAllAgentsLink);

            let modalFooter = document.createElement('div');
            modalFooter.classList.add("modal-footer");
            modalFooter.appendChild(closeButton);
            modalFooter.appendChild(newConversationSubmitButton);
            modalBody.appendChild(modalFooter);

            modalContent.appendChild(modalBody);
            modal.appendChild(modalContent);
            document.body.appendChild(modal);
        }

        function refreshChatSessionsPanel() {
            fetch('/api/chat/sessions', { method: "GET" })
                .then(response => response.json())
                .then(data => {
                    let conversationListBody = document.getElementById("conversation-list-body");
                    conversationListBody.innerHTML = "";
                    let conversationListBodyHeader = document.getElementById("conversation-list-header");

                    let chatBody = document.getElementById("chat-body");
                    conversationId = chatBody.dataset.conversationId;

                    if (data.length > 0) {
                        conversationListBodyHeader.style.display = "inline-flex";
                        for (let index in data) {
                            let conversation = data[index];
                            let conversationButton = document.createElement('div');
                            let incomingConversationId = conversation["conversation_id"];
                            const conversationTitle = conversation["slug"] || `New conversation 🌱`;
                            conversationButton.textContent = conversationTitle;
                            conversationButton.classList.add("conversation-button");
                            if (incomingConversationId == conversationId) {
                                conversationButton.classList.add("selected-conversation");
                            }
                            conversationButton.addEventListener('click', function() {
                                let chatBody = document.getElementById("chat-body");
                                chatBody.innerHTML = "";
                                chatBody.dataset.conversationId = incomingConversationId;
                                chatBody.dataset.conversationTitle = conversationTitle;
                                loadChat();
                            });
                            let threeDotMenu = document.createElement('div');
                            threeDotMenu.classList.add("three-dot-menu");
                            let threeDotMenuButton = document.createElement('button');
                            threeDotMenuButton.innerHTML = "⋮";
                            threeDotMenuButton.classList.add("three-dot-menu-button");
                            threeDotMenuButton.addEventListener('click', function(event) {
                                event.stopPropagation();

                                let existingChildren = threeDotMenu.children;

                                if (existingChildren.length > 1) {
                                    // Skip deleting the first, since that's the menu button.
                                    for (let i = 1; i < existingChildren.length; i++) {
                                        existingChildren[i].remove();
                                    }
                                    return;
                                }

                                let conversationMenu = document.createElement('div');
                                conversationMenu.classList.add("conversation-menu");

                                let editTitleButton = document.createElement('button');
                                editTitleButton.innerHTML = "Rename";
                                editTitleButton.classList.add("edit-title-button");
                                editTitleButton.classList.add("three-dot-menu-button-item");
                                editTitleButton.addEventListener('click', function(event) {
                                    event.stopPropagation();

                                    let conversationMenuChildren = conversationMenu.children;

                                    let totalItems = conversationMenuChildren.length;

                                    for (let i = totalItems - 1; i >= 0; i--) {
                                        conversationMenuChildren[i].remove();
                                    }

                                    // Create a dialog box to get new title for conversation
                                    let conversationTitleInputBox = document.createElement('div');
                                    conversationTitleInputBox.classList.add("conversation-title-input-box");
                                    let conversationTitleInput = document.createElement('input');
                                    conversationTitleInput.classList.add("conversation-title-input");

                                    conversationTitleInput.value = conversationTitle;

                                    conversationTitleInput.addEventListener('click', function(event) {
                                        event.stopPropagation();
                                    });
                                    conversationTitleInput.addEventListener('keydown', function(event) {
                                        if (event.key === "Enter") {
                                            event.preventDefault();
                                            conversationTitleInputButton.click();
                                        }
                                    });

                                    conversationTitleInputBox.appendChild(conversationTitleInput);
                                    let conversationTitleInputButton = document.createElement('button');
                                    conversationTitleInputButton.innerHTML = "Save";
                                    conversationTitleInputButton.classList.add("three-dot-menu-button-item");
                                    conversationTitleInputButton.addEventListener('click', function(event) {
                                        event.stopPropagation();
                                        let newTitle = conversationTitleInput.value;
                                        if (newTitle != null) {
                                            let editURL = `/api/chat/title?client=web&conversation_id=${incomingConversationId}&title=${newTitle}`;
                                            fetch(editURL , { method: "PATCH" })
                                                .then(response => response.ok ? response.json() : Promise.reject(response))
                                                .then(data => {
                                                    conversationButton.textContent = newTitle;
                                                })
                                                .catch(err => {
                                                    return;
                                                });
                                        conversationTitleInputBox.remove();
                                    }});
                                    conversationTitleInputBox.appendChild(conversationTitleInputButton);
                                    conversationMenu.appendChild(conversationTitleInputBox);
                                });
                                conversationMenu.appendChild(editTitleButton);
                                threeDotMenu.appendChild(conversationMenu);

                                let shareButton = document.createElement('button');
                                shareButton.innerHTML = "Share";
                                shareButton.type = "button";
                                shareButton.classList.add("share-conversation-button");
                                shareButton.classList.add("three-dot-menu-button-item");
                                shareButton.addEventListener('click', function(event) {
                                    event.preventDefault();
                                    let confirmation = confirm('Are you sure you want to share this chat session? This will make the conversation public.');
                                    if (!confirmation) return;
                                    let duplicateURL = `/api/chat/share?client=web&conversation_id=${incomingConversationId}`;
                                    fetch(duplicateURL , { method: "POST" })
                                        .then(response => response.ok ? response.json() : Promise.reject(response))
                                        .then(data => {
                                            if (data.status == "ok") {
                                                flashStatusInChatInput("✅ Conversation shared successfully");
                                            }
                                            // Make a pop-up that shows data.url to share the conversation
                                            let shareURL = data.url;
                                            let shareModal = document.createElement('div');
                                            shareModal.classList.add("modal");
                                            shareModal.id = "share-conversation-modal";
                                            let shareModalContent = document.createElement('div');
                                            shareModalContent.classList.add("modal-content");
                                            let shareModalHeader = document.createElement('div');
                                            shareModalHeader.classList.add("modal-header");
                                            let shareModalTitle = document.createElement('h2');
                                            shareModalTitle.textContent = "Share Conversation";
                                            let shareModalCloseButton = document.createElement('button');
                                            shareModalCloseButton.classList.add("modal-close-button");
                                            shareModalCloseButton.innerHTML = "&times;";
                                            shareModalCloseButton.addEventListener('click', function() {
                                                shareModal.remove();
                                            });
                                            shareModalHeader.appendChild(shareModalTitle);
                                            shareModalHeader.appendChild(shareModalCloseButton);
                                            shareModalContent.appendChild(shareModalHeader);
                                            let shareModalBody = document.createElement('div');
                                            shareModalBody.classList.add("modal-body");
                                            let shareModalText = document.createElement('p');
                                            shareModalText.textContent = "The link has been copied to your clipboard. Use it to share your conversation with others!";
                                            let shareModalLink = document.createElement('input');
                                            shareModalLink.setAttribute("value", shareURL);
                                            shareModalLink.setAttribute("readonly", "");
                                            shareModalLink.classList.add("share-link");
                                            let copyButton = document.createElement('button');
                                            copyButton.textContent = "Copy";
                                            copyButton.addEventListener('click', function() {
                                                shareModalLink.select();
                                                document.execCommand('copy');
                                            });
                                            copyButton.id = "copy-share-url-button";
                                            shareModalBody.appendChild(shareModalText);
                                            shareModalBody.appendChild(shareModalLink);
                                            shareModalBody.appendChild(copyButton);
                                            shareModalContent.appendChild(shareModalBody);
                                            shareModal.appendChild(shareModalContent);
                                            document.body.appendChild(shareModal);
                                            shareModalLink.select();
                                            document.execCommand('copy');
                                        })
                                        .catch(err => {
                                            return;
                                        });
                                });
                                conversationMenu.appendChild(shareButton);

                                let deleteButton = document.createElement('button');
                                deleteButton.type = "button";
                                deleteButton.innerHTML = "Delete";
                                deleteButton.classList.add("delete-conversation-button");
                                deleteButton.classList.add("three-dot-menu-button-item");
                                deleteButton.addEventListener('click', function(event) {
                                    event.preventDefault();
                                    // Ask for confirmation before deleting chat session
                                    let confirmation = confirm('Are you sure you want to delete this chat session?');
                                    if (!confirmation) return;
                                    let deleteURL = `/api/chat/history?client=web&conversation_id=${incomingConversationId}`;
                                    fetch(deleteURL , { method: "DELETE" })
                                        .then(response => response.ok ? response.json() : Promise.reject(response))
                                        .then(data => {
                                            let chatBody = document.getElementById("chat-body");
                                            chatBody.innerHTML = "";
                                            chatBody.dataset.conversationId = "";
                                            chatBody.dataset.conversationTitle = "";
                                            loadChat();
                                        })
                                        .catch(err => {
                                            flashStatusInChatInput("⛔️ Failed to clear conversation history");
                                        });
                                });
                                conversationMenu.appendChild(deleteButton);
                                threeDotMenu.appendChild(conversationMenu);
                            });
                            threeDotMenu.appendChild(threeDotMenuButton);
                            conversationButton.appendChild(threeDotMenu);
                            conversationListBody.appendChild(conversationButton);
                        }
                    }
                })
                .catch(err => {
                    console.log(err);
                    return;
                });
        }

        let sendMessageTimeout;
        let mediaRecorder;
        function speechToText(event) {
            event.preventDefault();
            const speakButtonImg = document.getElementById('speak-button-img');
            const stopRecordButtonImg = document.getElementById('stop-record-button-img');
            const sendButtonImg = document.getElementById('send-button-img');
            const stopSendButtonImg = document.getElementById('stop-send-button-img');
            const chatInput = document.getElementById('chat-input');

            const sendToServer = (audioBlob) => {
                const formData = new FormData();
                formData.append('file', audioBlob);

                fetch('/api/transcribe?client=web', { method: 'POST', body: formData })
                    .then(response => response.ok ? response.json() : Promise.reject(response))
                    .then(data => { chatInput.value += data.text.trimStart(); autoResize(); })
                    .then(() => {
                        // Don't auto-send empty messages
                        if (chatInput.value.length === 0) return;

                        // Send message after 3 seconds, unless stop send button is clicked
                        sendButtonImg.style.display = 'none';
                        stopSendButtonImg.style.display = 'initial';

                        // Start the countdown timer UI
                        document.getElementById('countdown-circle').style.animation = "countdown 3s linear 1 forwards";

                        sendMessageTimeout = setTimeout(() => {
                            // Revert to showing send-button and hide the stop-send-button
                            sendButtonImg.style.display = 'initial';
                            stopSendButtonImg.style.display = 'none';

                            // Stop the countdown timer UI
                            document.getElementById('countdown-circle').style.animation = "none";

                            // Send message
                            chat();
                        }, 3000);
                    })
                    .catch(err => {
                        if (err.status === 501) {
                          flashStatusInChatInput("⛔️ Configure speech-to-text model on server.")
                        } else if (err.status === 422) {
                          flashStatusInChatInput("⛔️ Audio file to large to process.")
                        } else if (err.status === 429) {
                            flashStatusInChatInput("⛔️ " + err.statusText);
                        } else {
                          flashStatusInChatInput("⛔️ Failed to transcribe audio.")
                        }
                    });
            };

            const handleRecording = (stream) => {
                const audioChunks = [];
                const recordingConfig = { mimeType: 'audio/webm' };
                mediaRecorder = new MediaRecorder(stream, recordingConfig);

                mediaRecorder.addEventListener("dataavailable", function(event) {
                    if (event.data.size > 0) audioChunks.push(event.data);
                });

                mediaRecorder.addEventListener("stop", function() {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                    sendToServer(audioBlob);
                });

                mediaRecorder.start();
                speakButtonImg.style.display = 'none';
                stopRecordButtonImg.style.display = 'initial';
            };

            // Toggle recording
            if (!mediaRecorder || mediaRecorder.state === 'inactive' || event.type === 'touchstart') {
                navigator.mediaDevices
                ?.getUserMedia({ audio: true })
                .then(handleRecording)
                .catch((e) => {
                    flashStatusInChatInput("⛔️ Failed to access microphone");
                });
            } else if (mediaRecorder.state === 'recording' || event.type === 'touchend' || event.type === 'touchcancel') {
                mediaRecorder.stop();
                mediaRecorder.stream.getTracks().forEach(track => track.stop());
                mediaRecorder = null;
                speakButtonImg.style.display = 'initial';
                stopRecordButtonImg.style.display = 'none';
            }
        }

        function cancelSendMessage() {
            // Cancel the chat() call if the stop-send-button is clicked
            clearTimeout(sendMessageTimeout);

            // Revert to showing send-button and hide the stop-send-button
            document.getElementById('stop-send-button-img').style.display = 'none';
            document.getElementById('send-button-img').style.display = 'initial';

            // Stop the countdown timer UI
            document.getElementById('countdown-circle').style.animation = "none";
        };

        function handleCollapseSidePanel() {
            document.getElementById('side-panel').classList.toggle('collapsed');
            document.getElementById('new-conversation').classList.toggle('collapsed');
            document.getElementById('existing-conversations').classList.toggle('collapsed');
            document.getElementById('side-panel-collapse').style.transform = document.getElementById('side-panel').classList.contains('collapsed') ? 'rotate(0deg)' : 'rotate(180deg)';
        }
    </script>
    <body>
        <div id="khoj-empty-container" class="khoj-empty-container">
        </div>

        <!--Add Header Logo and Nav Pane-->
        {% import 'utils.html' as utils %}
        {{ utils.heading_pane(user_photo, username, is_active, has_documents) }}
        <div id="chat-section-wrapper">
            <div id="side-panel-wrapper">
                <div id="side-panel">
                    <div id="new-conversation">
                       <div id="conversation-list-header" style="display: none;">Conversations</div>
                       <button class="side-panel-button" id="new-conversation-button" onclick="createNewConversation()">
                            New
                            <svg class="new-convo-button" viewBox="0 0 40 40" fill="#000000" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">
                                <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>
                            </svg>
                        </button>
                    </div>
                    <div id="existing-conversations">
                        <div id="conversation-list">
                            <div id="conversation-list-body"></div>
                        </div>
                    </div>
                    <div id="connection-status" class="inline-chat-link" style="display: flex; align-items: center; border-top: 1px solid black;">
                        <div id="connection-status-icon" style="width: 10px; height: 10px; border-radius: 50%; margin-right: 5px;"></div>
                        <div id="connection-status-text" style="margin: 5px;"></div>
                    </div>
                    <a id="agent-link" class="inline-chat-link" href="">
                        <div id="agent-metadata" style="display: none;">
                            Current Agent
                            <div id="agent-metadata-content">
                                <div id="agent-avatar-wrapper">
                                    <img id="agent-avatar" src="" alt="Agent Avatar" />
                                </div>
                                <div id="agent-name-wrapper">
                                    <div id="agent-name"></div>
                                    <div id="agent-owned-by-user" style="display: none;">Edit</div>
                                </div>
                            </div>
                        </div>
                    </a>
                </div>
                <div id="collapse-side-panel">
                    <button
                        class="side-panel-button"
                        id="collapse-side-panel-button"
                        onclick="handleCollapseSidePanel()"
                    >
                        <svg id="side-panel-collapse" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M7.82054 20.7313C8.21107 21.1218 8.84423 21.1218 9.23476 20.7313L15.8792 14.0868C17.0505 12.9155 17.0508 11.0167 15.88 9.84497L9.3097 3.26958C8.91918 2.87905 8.28601 2.87905 7.89549 3.26958C7.50497 3.6601 7.50497 4.29327 7.89549 4.68379L14.4675 11.2558C14.8581 11.6464 14.8581 12.2795 14.4675 12.67L7.82054 19.317C7.43002 19.7076 7.43002 20.3407 7.82054 20.7313Z" fill="#0F0F0F"/>
                        </svg>
                    </button>
                </div>
            </div>
            <div id="chat-body-wrapper">
                <!-- Chat Body -->
                <div id="chat-body"></div>

                <!-- Chat Suggestions -->
                <div id="question-starters" style="display: none;"></div>

                <!-- Chat Footer -->
                <div id="chat-footer">
                    <div id="chat-tooltip" style="display: none;"></div>
                    <div id="input-row">
                        <button id="upload-file-button" class="input-row-button" onclick="openFileBrowser()">
                            <svg id="upload-file-button-img" class="input-row-button-img" alt="Upload File" width="183px" height="183px" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#000000" stroke-width="0.9600000000000002" transform="matrix(1, 0, 0, 1, 0, 0)rotate(-45)">
                                <g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g id="attachment"> <g id="attachment_2"> <path id="Combined Shape" fill-rule="evenodd" clip-rule="evenodd" d="M26.4252 29.1104L39.5729 15.9627C42.3094 13.2262 42.3094 8.78901 39.5729 6.05248C36.8364 3.31601 32.4015 3.31601 29.663 6.05218L16.4487 19.2665L16.4251 19.2909L8.92989 26.7861C5.02337 30.6926 5.02337 37.0238 8.92989 40.9303C12.8344 44.8348 19.1656 44.8348 23.0701 40.9303L41.7835 22.2169C42.174 21.8264 42.174 21.1933 41.7835 20.8027C41.3929 20.4122 40.7598 20.4122 40.3693 20.8027L21.6559 39.5161C18.5324 42.6396 13.4676 42.6396 10.3441 39.5161C7.21863 36.3906 7.21863 31.3258 10.3441 28.2003L30.1421 8.4023L30.1657 8.37788L31.0769 7.4667C33.0341 5.51117 36.2032 5.51117 38.1587 7.4667C40.1142 9.42217 40.1142 12.593 38.1587 14.5485L28.282 24.4252C28.2748 24.4319 28.2678 24.4388 28.2608 24.4458L25.0064 27.7008L24.9447 27.7625C24.9437 27.7635 24.9427 27.7644 24.9418 27.7654L17.3988 35.3097C16.6139 36.0934 15.3401 36.0934 14.5545 35.3091C13.7714 34.5247 13.7714 33.2509 14.5557 32.4653L24.479 22.544C24.8696 22.1535 24.8697 21.5203 24.4792 21.1298C24.0887 20.7392 23.4555 20.7391 23.065 21.1296L13.141 31.0516C11.5766 32.6187 11.5766 35.1569 13.1403 36.7233C14.7079 38.2882 17.2461 38.2882 18.8125 36.7245L26.3589 29.1767L26.4252 29.1104Z" fill="#000000"></path></g> </g> </g>
                            </svg>
                        </button>
                        <textarea id="chat-input" class="option" oninput="onChatInput()" onkeydown=incrementalChat(event) autofocus="autofocus" placeholder="Type / to see a list of commands"></textarea>
                        <button id="speak-button" class="input-row-button"
                            ontouchstart="speechToText(event)" ontouchend="speechToText(event)" ontouchcancel="speechToText(event)" onmousedown="speechToText(event)">
                            <svg id="speak-button-img" class="input-row-button-img" alt="Transcribe" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                <path d="M3.5 6.5A.5.5 0 0 1 4 7v1a4 4 0 0 0 8 0V7a.5.5 0 0 1 1 0v1a5 5 0 0 1-4.5 4.975V15h3a.5.5 0 0 1 0 1h-7a.5.5 0 0 1 0-1h3v-2.025A5 5 0 0 1 3 8V7a.5.5 0 0 1 .5-.5z"/>
                                <path d="M10 8a2 2 0 1 1-4 0V3a2 2 0 1 1 4 0v5zM8 0a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V3a3 3 0 0 0-3-3z"/>
                            </svg>
                            <svg id="stop-record-button-img" style="display: none" class="input-row-button-img" alt="Stop Transcribing" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                <path d="M5 6.5A1.5 1.5 0 0 1 6.5 5h3A1.5 1.5 0 0 1 11 6.5v3A1.5 1.5 0 0 1 9.5 11h-3A1.5 1.5 0 0 1 5 9.5v-3z"/>
                            </svg>
                        </button>
                        <button id="send-button" class="input-row-button" alt="Send message">
                            <svg id="send-button-img" onclick="chat()" class="input-row-button-img" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-7.5 3.5a.5.5 0 0 1-1 0V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11.5z"/>
                            </svg>
                            <svg id="stop-send-button-img" onclick="cancelSendMessage()" style="display: none" class="input-row-button-img" alt="Stop Message Send" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                <circle id="countdown-circle" class="countdown-circle" cx="8" cy="8" r="7" />
                                <path d="M5 6.5A1.5 1.5 0 0 1 6.5 5h3A1.5 1.5 0 0 1 11 6.5v3A1.5 1.5 0 0 1 9.5 11h-3A1.5 1.5 0 0 1 5 9.5v-3z"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </body>
    <script>
        // Set the active nav pane
        let chatNav = document.getElementById("chat-nav");
        if (chatNav) {
            chatNav.classList.add("khoj-nav-selected");
        }
    </script>
    <style>
        html, body {
            height: 100%;
            width: 100%;
            padding: 0px;
            margin: 0px;
        }
        body {
            display: grid;
            background: var(--background-color);
            color: var(--main-text-color);
            text-align: center;
            font-family: var(--font-family);
            font-size: medium;
            font-weight: 300;
            line-height: 1.5em;
            height: 100vh;
            margin: 0;
        }
        body > * {
            padding: 10px;
            margin: 10px;
        }

        div.collapsed {
            display: none;
        }

        div.expanded {
            display: block;
        }

        div.references {
            padding-top: 8px;
        }
        div.reference {
            display: grid;
            grid-template-rows: auto;
            grid-auto-flow: row;
            grid-column-gap: 10px;
            grid-row-gap: 10px;
            margin: 10px;
        }

        div.expanded.reference-section {
            display: grid;
            grid-template-rows: auto;
            grid-auto-flow: row;
            grid-column-gap: 10px;
            grid-row-gap: 10px;
            margin: 10px;
        }

        div#question-starters {
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            grid-column-gap: 8px;
        }

        button.question-starter {
            background: var(--background-color);
            color: var(--main-text-color);
            border: 1px solid var(--main-text-color);
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.2s ease-in-out;
            text-align: left;
            max-height: 75px;
            transition: max-height 0.3s ease-in-out;
            overflow: hidden;
        }
        button.question-starter:hover {
            background: var(--primary-hover);
        }

        button.reference-button {
            background: var(--background-color);
            color: var(--main-text-color);
            border: 1px solid var(--main-text-color);
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.2s ease-in-out;
            text-align: left;
            max-height: 75px;
            transition: max-height 0.3s ease-in-out;
            overflow: hidden;
        }
        button.reference-button.expanded {
            max-height: none;
            white-space: pre-wrap;
        }

        button.reference-button::before {
            content: "▶";
            margin-right: 5px;
            display: inline-block;
            transition: transform 0.1s ease-in-out;
        }

        button.reference-button.expanded::before,
        button.reference-button:active:before,
        button.reference-button[aria-expanded="true"]::before {
            transform: rotate(90deg);
        }

        button.reference-expand-button {
            background: var(--background-color);
            color: var(--main-text-color);
            border: 1px dotted var(--main-text-color);
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.4s ease-in-out;
            text-align: left;
        }

        button.reference-expand-button:hover {
            background: var(--primary-hover);
        }

        code.chat-response {
            background: var(--primary-hover);
            color: var(--primary-inverse);
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
        }

        input.conversation-title-input {
            font-family: var(--font-family);
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            padding: 5px;
            border: 1px solid var(--main-text-color);
            border-radius: 5px;
            margin: 4px;
        }

        input.conversation-title-input:focus {
            outline: none;
        }

        #chat-section-wrapper {
            display: grid;
            grid-template-columns: auto 1fr;
            grid-column-gap: 10px;
            grid-row-gap: 10px;
            padding: 10px;
            margin: 10px;
            overflow-y: scroll;
        }

        #chat-body-wrapper {
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        #side-panel {
            width: 250px;
            padding: 10px;
            background: var(--background-color);
            border-radius: 5px;
            box-shadow: 0 0 11px #aaa;
            text-align: left;
            transition: width 0.3s ease-in-out;
            max-height: 100%;
            display: grid;
            grid-template-rows: auto 1fr auto;
        }

        div#existing-conversations {
            max-height: 95%;
            overflow-y: auto;
        }

        div#side-panel.collapsed {
            width: 0;
            padding: 0;
            display: block;
            overflow: hidden;
        }

        div#collapse-side-panel {
            align-self: center;
            padding: 8px;
        }

        div#conversation-list-body {
            display: grid;
            grid-template-columns: 1fr;
            grid-gap: 8px;
        }

        div#conversation-list {
            height: 1px;
        }

        div#side-panel-wrapper {
            display: flex;
        }

        #chat-body {
            height: 100%;
            font-size: medium;
            margin: 0px;
            line-height: 20px;
            overflow-y: scroll;
            overflow-x: hidden;
            transition: background-color 0.2s;
            transition: opacity 0.2s;
        }

        #chat-body.dragover {
            background-color: var(--primary-active);
        }

        .relative-position {
            position: relative;
        }

        #chat-body.dragover {
            opacity: 50%;
        }

        div.dropzone-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: #333;
            z-index: 9999; /* This is the important part */
            pointer-events: none;
        }

        div.loading-screen {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: #333;
            z-index: 9999; /* This is the important part */
        }

        /* add chat metatdata to bottom of bubble */
        .chat-message::after {
            content: attr(data-meta);
            display: block;
            font-size: x-small;
            color: var(--main-text-color);
            margin: -8px 4px 0px 0px;
        }
        /* move message by khoj to left */
        .chat-message.khoj {
            margin-left: auto;
            text-align: left;
            height: fit-content;
        }
        /* move message by you to right */
        .chat-message.you {
            margin-right: auto;
            text-align: right;
            height: fit-content;
        }
        /* basic style chat message text */
        .chat-message-text {
            margin: 10px;
            border-radius: 10px;
            padding: 10px;
            position: relative;
            display: inline-block;
            max-width: 80%;
            text-align: left;
            white-space: pre-line;
        }
        /* color chat bubble by khoj blue */
        .chat-message-text.khoj {
            color: var(--primary-inverse);
            background: var(--primary);
            margin-left: auto;
        }
        .chat-message-text ol,
        .chat-message-text ul {
            white-space: normal;
            margin: 0;
        }
        .chat-message-text-response {
            margin-bottom: 0px;
        }

        /* Spinner symbol when the chat message is loading */
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid var(--primary-inverse);
            border-radius: 50%;
            width: 12px;
            height: 12px;
            animation: spin 2s linear infinite;
            margin: 0px 0px 0px 10px;
            display: inline-block;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        /* add left protrusion to khoj chat bubble */
        .chat-message-text.khoj:after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: -7px;
            border: 10px solid transparent;
            border-top-color: var(--primary);
            border-bottom: 0;
            transform: rotate(-60deg);
        }
        /* color chat bubble by you dark grey */
        .chat-message-text.you {
            color: #f8fafc;
            background: #475569;
            margin-right: auto;
        }
        /* add right protrusion to you chat bubble */
        .chat-message-text.you:after {
            content: '';
            position: absolute;
            top: 91%;
            right: -2px;
            border: 10px solid transparent;
            border-left-color: var(--main-text-color);
            border-right: 0;
            margin-top: -10px;
            transform: rotate(-60deg)
        }
        img.text-to-image {
            max-width: 60%;
        }
        h3 > img.text-to-image {
            height: 24px;
            vertical-align: sub;
        }

        #chat-footer {
            padding: 0;
            margin: 8px;
            display: grid;
            grid-template-columns: minmax(70px, 100%);
            grid-column-gap: 10px;
            grid-row-gap: 10px;
        }
        #input-row {
            display: grid;
            grid-template-columns: 32px auto 40px 32px;
            grid-column-gap: 10px;
            grid-row-gap: 10px;
            background: var(--background-color);
            align-items: center;
        }
        .option:hover {
            box-shadow: 0 0 11px #aaa;
        }

        .helpoption:hover {
            background-color: #d9d9d9;
        }

        #chat-input {
            font-family: var(--font-family);
            font-size: medium;
            height: 48px;
            border-radius: 16px;
            resize: none;
            overflow-y: hidden;
            max-height: 200px;
            box-sizing: border-box;
            padding: 4px 0 0 12px;
            line-height: 1.5em;
            margin: 0;
        }
        #chat-input:focus {
            outline: none !important;
        }
        .input-row-button {
            background: var(--background-color);
            border: none;
            box-shadow: none;
            border-radius: 50%;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.3s ease-in-out;
            width: 40px;
            height: 40px;
            margin-top: -2px;
            margin-left: -5px;
        }

        .side-panel-button {
            background: none;
            border: none;
            box-shadow: none;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.3s ease-in-out;
            border-radius: 5%;;
            font-family: var(--font-family);
        }

        svg#side-panel-collapse {
            width: 30px;
            height: 30px;
        }

        .side-panel-button:hover,
        .input-row-button:hover {
            background: var(--primary-hover);
        }
        .side-panel-button:active,
        .input-row-button:active {
            background: var(--primary-active);
        }

        .input-row-button-img {
            width: 24px;
            height: 24px;
        }
        #send-button {
            padding: 0;
            position: relative;
        }
        #send-button-img {
            width: 28px;
            height: 28px;
            background: var(--primary-hover);
            border-radius: 50%;
        }

        #stop-send-button-img {
            position: absolute;
            top: 6px;
            right: 6px;
            width: 28px;
            height: 28px;
            transform: rotateY(-180deg) rotateZ(-90deg);
        }
        #countdown-circle {
            stroke-dasharray: 44px;  /* The circumference of the circle with 7px radius */
            stroke-dashoffset: 0px;
            stroke-linecap: round;
            stroke-width: 1px;
            stroke: var(--main-text-color);
            fill: none;
        }
        @keyframes countdown {
            from {
                stroke-dashoffset: 0px;
            }
            to {
                stroke-dashoffset: -44px;  /* The circumference of the circle with 7px radius */
            }
        }

        .option-enabled {
            box-shadow: 0 0 12px rgb(119, 156, 46);
        }

        .option-enabled:focus {
            outline: none !important;
            border:1px solid #475569;
            box-shadow: 0 0 16px var(--primary);
        }

        a.inline-chat-link {
            color: var(--main-text-color);
            text-decoration: none;
            border-bottom: 1px dotted var(--main-text-color);
        }

        a.reference-link {
            color: var(--main-text-color);
            border-bottom: 1px dotted var(--main-text-color);
        }

        button.copy-button {
            border-radius: 4px;
            background-color: var(--background-color);
            border: 1px solid var(--main-text-color);
            text-align: center;
            font-size: 16px;
            transition: all 0.5s;
            cursor: pointer;
            padding: 4px;
            float: right;
        }

        button.thumbs-up-button {
            border-radius: 4px;
            background-color: var(--background-color);
            border: 1px solid var(--main-text-color);
            text-align: center;
            font-size: 16px;
            transition: all 0.5s;
            cursor: pointer;
            padding: 4px;
            float: right;
            margin-right: 4px;
        }

        button.thumbs-down-button {
            border-radius: 4px;
            background-color: var(--background-color);
            border: 1px solid var(--main-text-color);
            text-align: center;
            font-size: 16px;
            transition: all 0.5s;
            cursor: pointer;
            padding: 4px;
            float: right;
            margin-right:4px;
        }

        button.copy-button span {
            cursor: pointer;
            display: inline-block;
            position: relative;
            transition: 0.5s;
        }

        img.copy-icon {
            width: 18px;
            height: 18px;
        }

        img.thumbs-up-icon {
            width: 18px;
            height: 18px;
        }

        img.thumbs-down-icon {
            width: 18px;
            height: 18px;
        }

        button.copy-button:hover {
            background-color: var(--primary-hover);
            color: #f5f5f5;
        }

        button.thumbs-up-button:hover {
            background-color: var(--primary-hover);
            color: #f5f5f5;
        }

        button.thumbs-down-button:hover {
            background-color: var(--primary-hover);
            color: #f5f5f5;
        }

        pre {
            text-wrap: unset;
        }

        @media (pointer: coarse), (hover: none) {
            abbr[title] {
                position: relative;
                padding-left: 4px;  /* space references out to ease tapping */
            }
            abbr[title]:focus:after {
                content: attr(title);

                /* position tooltip */
                position: absolute;
                left: 16px;  /* open tooltip to right of ref link, instead of on top of it */
                width: auto;
                z-index: 1;  /* show tooltip above chat messages */

                /* style tooltip */
                background-color: #aaa;
                color: #f8fafc;
                border-radius: 2px;
                box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.4);
                font-size: 14px;
                padding: 2px 4px;
            }
        }
        @media only screen and (max-width: 700px) {
            body {
                grid-template-columns: 1fr;
                grid-template-rows: auto auto minmax(80px, 100%) auto;
            }
            body > * {
                grid-column: 1;
            }
            #chat-footer {
                padding: 0;
                margin: 4px;
                grid-template-columns: auto;
            }
            img.text-to-image {
                max-width: 100%;
            }
            #clear-chat-button {
                margin-left: 0;
            }

            div#side-panel.collapsed {
                width: 0px;
                display: block;
                overflow: hidden;
                padding: 0;
            }

            svg#side-panel-collapse {
                width: 24px;
                height: 24px;
            }

            #chat-body-wrapper {
                min-width: 0;
            }

            div#chat-section-wrapper {
                padding: 4px;
                margin: 4px;
                grid-column-gap: 4px;
            }
            div#collapse-side-panel {
                align-self: center;
                padding: 0px;
            }
        }
        @media only screen and (min-width: 700px) {
            body {
                grid-template-columns: auto min(90vw, 100%) auto;
                grid-template-rows: auto auto minmax(80px, 100%) auto;
            }
            body > * {
                grid-column: 2;
            }
        }

        div#chat-tooltip {
            text-align: left;
            font-size: medium;
        }
        div#chat-tooltip:hover {
            cursor: pointer;
        }

        svg.new-convo-button {
            width: 20px;
            margin-left: 5px;
        }

        div#new-conversation {
            display: grid;
            grid-auto-flow: column;
            font-size: large;
            text-align: left;
            border-bottom: 1px solid var(--main-text-color);
            margin-top: 8px;
            margin-bottom: 8px;
        }

        button#copy-share-url-button,
        button#new-conversation-button {
            display: inline-flex;
            align-items: center;
            justify-self: end;
        }

        div.conversation-button {
            background: var(--background-color);
            color: var(--main-text-color);
            border: 1px solid var(--main-text-color);
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.2s ease-in-out;
            text-align: left;
            display: flex;
            position: relative;
            margin-right: 8px;
        }

        .three-dot-menu {
            display: block;
            border-radius: 5px;
            position: absolute;
            right: 4px;
            top: 4px;
        }

        button.three-dot-menu-button-item {
            background: var(--background-color);
            color: var(--main-text-color);
            border: none;
            box-shadow: none;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.3s ease-in-out;
            font-family: var(--font-family);
            border-radius: 4px;
            right: 0;
        }

        button.three-dot-menu-button-item:hover {
            background: var(--primary-hover);
            color: var(--primary-inverse);
        }

        .three-dot-menu-button {
            background: var(--background-color);
            border: none;
            box-shadow: none;
            font-size: 14px;
            font-weight: 300;
            line-height: 1.5em;
            cursor: pointer;
            transition: background 0.3s ease-in-out;
            font-family: var(--font-family);
            border-radius: 4px;
            right: 0;
        }

        .conversation-button:hover .three-dot-menu {
            display: block;
        }

        div.conversation-menu {
            position: absolute;
            z-index: 1;
            top: 100%;
            right: 0;
            text-align: right;
            background-color: var(--background-color);
            border: 1px solid var(--main-text-color);
            border-radius: 5px;
            padding: 5px;
            box-shadow: 0 0 11px #aaa;
        }

        div.conversation-button:hover {
            background: var(--primary-hover);
            color: var(--primary-inverse);
        }

        div.selected-conversation {
            background: var(--primary-hover) !important;
            color: var(--primary-inverse) !important;
        }

        @keyframes gradient {
            0% {
                background-position: 0% 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0% 50%;
            }
        }

        a.khoj-logo {
            text-align: center;
        }

        div.khoj-empty-container {
            margin: 0px;
            padding: 0px;
        }

        p {
            margin: 0;
        }

        div.programmatic-output {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 3px;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
            color: #333;
            font-family: monospace;
            font-size: 14px;
            line-height: 1.5;
            margin: 10px 0;
            overflow-x: auto;
            padding: 10px;
            white-space: pre-wrap;
        }

        .loading-spinner {
            display: inline-block;
            position: relative;
            width: 80px;
            height: 80px;
        }
        .loading-spinner div {
            position: absolute;
            border: 4px solid var(--primary-hover);
            opacity: 1;
            border-radius: 50%;
            animation: lds-ripple 0.5s cubic-bezier(0, 0.2, 0.8, 1) infinite;
        }
        .loading-spinner div:nth-child(2) {
            animation-delay: -0.5s;
        }
        @keyframes lds-ripple {
            0% {
                top: 36px;
                left: 36px;
                width: 0;
                height: 0;
                opacity: 1;
                border-color: var(--primary-hover);
            }
            50% {
                border-color: var(--flower);
            }
            100% {
                top: 0px;
                left: 0px;
                width: 72px;
                height: 72px;
                opacity: 0;
                border-color: var(--water);
            }
        }

        #agent-metadata-content {
            display: grid;
            grid-template-columns: auto 1fr;
            padding: 10px;
            background-color: var(--primary);
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
            margin-bottom: 20px;
        }

        #agent-metadata {
            border-top: 1px solid black;
            padding-top: 10px;
        }

        #agent-avatar-wrapper {
            margin-right: 10px;
        }

        #agent-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
        }

        #agent-name-wrapper {
            display: grid;
            align-items: center;
        }

        #agent-name {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        #agent-owned-by-user {
            font-size: 12px;
            color: #007BFF;
            margin-top: 5px;
        }

        .modal {
            position: fixed; /* Stay in place */
            z-index: 1; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%; /* Full height */
            background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
            margin: 0px;
        }

        .modal-content {
            margin: 15% auto; /* 15% from the top and centered */
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
            text-align: left;
            background: var(--background-color);
            border-radius: 5px;
            box-shadow: 0 0 11px #aaa;
            text-align: left;
        }

        .modal-header {
            display: grid;
            grid-template-columns: 1fr auto;
            color: var(--main-text-color);
            align-items: baseline;
        }

        .modal-header h2 {
            margin: 0;
            text-align: left;
        }

        .modal-body {
            display: grid;
            grid-auto-flow: row;
            gap: 8px;
        }

        .modal-body a {
            /* text-decoration: none; */
            color: var(--summer-sun);
        }

        .modal-close-button {
            margin: 0;
            font-size: 20px;
            background: none;
            border: none;
            color: var(--summer-sun);
        }

        .modal-close-button:hover,
        .modal-close-button:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

        #new-conversation-form {
            display: flex;
            flex-direction: column;
        }

        #new-conversation-form label,
        #new-conversation-form input,
        #new-conversation-form button {
            margin-bottom: 10px;
        }

        #new-conversation-form button {
            cursor: pointer;
        }

        .modal-footer {
            display: grid;
            grid-template-columns: 1fr 1fr;
            grid-gap: 12px;
        }

        .modal-body button {
            cursor: pointer;
            border-radius: 12px;
            padding: 8px;
            border: 1px solid var(--main-text-color);
        }

        .share-link {
            display: block;
            width: 100%;
            padding: 10px;
            margin-top: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #f9f9f9;
            font-family: 'Courier New', monospace;
            color: #333;
            font-size: 16px;
            box-sizing: border-box;
            transition: all 0.3s ease;
        }

        .share-link:focus {
            outline: none;
            border-color: #007BFF;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }

        button#copy-share-url-button,
        button#new-conversation-submit-button {
            background: var(--summer-sun);
            transition: background 0.2s ease-in-out;
        }

        button#close-button {
            background: var(--background-color);
            transition: background 0.2s ease-in-out;
        }

        button#copy-share-url-button:hover,
        button#new-conversation-submit-button:hover {
            background: var(--primary);
        }

        button#close-button:hover {
            background: var(--primary-hover);
        }

        .modal-body select {
            padding: 8px;
            border-radius: 12px;
            border: 1px solid var(--main-text-color);
        }


        .lds-ellipsis {
            display: inline-block;
            position: relative;
            width: 60px;
            height: 32px;
        }
        .lds-ellipsis div {
            position: absolute;
            top: 12px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--main-text-color);
            animation-timing-function: cubic-bezier(0, 1, 1, 0);
        }
        .lds-ellipsis div:nth-child(1) {
            left: 8px;
            animation: lds-ellipsis1 0.6s infinite;
        }
        .lds-ellipsis div:nth-child(2) {
            left: 8px;
            animation: lds-ellipsis2 0.6s infinite;
        }
        .lds-ellipsis div:nth-child(3) {
            left: 32px;
            animation: lds-ellipsis2 0.6s infinite;
        }
        .lds-ellipsis div:nth-child(4) {
            left: 56px;
            animation: lds-ellipsis3 0.6s infinite;
        }
        @keyframes lds-ellipsis1 {
            0% {
                transform: scale(0);
            }
            100% {
                transform: scale(1);
            }
        }
        @keyframes lds-ellipsis3 {
            0% {
                transform: scale(1);
            }
            100% {
                transform: scale(0);
            }
        }
        @keyframes lds-ellipsis2 {
            0% {
                transform: translate(0, 0);
            }
            100% {
                transform: translate(24px, 0);
            }
        }
    </style>
</html>
